package Events.gui.components;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

/**
 * Textfield that only accepts Integer values.
 * @author Edd Purcell
 *
 */
public class IntField extends JTextField {
	private static final long serialVersionUID = 1L;
	
	/**
	 * Creates a basic IntField with the normal Integer max value.
	 */
	public IntField(){
		this(Integer.MAX_VALUE);
	}
	
	/**
	 * Creates an IntField with a set max value.
	 * @param maxValue	max value the field can have
	 */
	public IntField(int maxValue){
		super();
		((IntDocument)(this.getDocument())).setMaxValue(maxValue);
	}
	
	/**
	 * Creates an IntField with a max value and number of columns.
	 * @param maxValue	max value the field can have
	 * @param columns	number of columns to show
	 */
	public IntField(int maxValue, int columns){
		super(columns);
		((IntDocument)(this.getDocument())).setMaxValue(maxValue);
	}
	
	protected Document createDefaultModel(){
		return new IntDocument();
	}
	
	/**
	 * Set a new max value of the IntField.
	 * @param maxValue	max value to use
	 */
	public void setMaxValue(int maxValue){
		((IntDocument)(this.getDocument())).setMaxValue(maxValue);
	}
	
	/**
	 * Get the integer in the IntField.
	 * @return	int stored in the field
	 */
	public int getInt(){
		String text = getText();
		if(text == null || text.length() == 0)
			return 0;
		return Integer.parseInt(text);
	}
	
	/**
	 * Set the int stored in the field.
	 * @param n	new int to store
	 */
	public void setInt(int n){
		setText(String.valueOf(n));
	}

	/**
	 * A Document to control what's allowed and not allowed in the IntField.
	 * @author Edd Purcell
	 *
	 */
	private static class IntDocument extends PlainDocument {
		private static final long serialVersionUID = 1L;
		
		private int maxValue;
		
		/**
		 * Creates a standard IntDocument with the max value set at the highest 
		 * value an Integer can be.
		 */
		public IntDocument(){
			this.maxValue = Integer.MAX_VALUE;
		}

		/**
		 * Checks to make sure that only integers are accepted values and never 
		 * exceed the maximum value allowed.
		 */
		public void insertString(int offs, String str, AttributeSet a)
	      throws BadLocationException
	    {
			if(str != null){
				try {
					int n = Integer.decode(str);
					if(Integer.parseInt(this.getText(0, offs) + n) <= maxValue)
						super.insertString(offs, str, a);
					else {
						remove(0, offs);
						super.insertString(0, String.valueOf(maxValue), a);
					}
				} catch(NumberFormatException e) {
					
				}
			}
		}
		
		/**
		 * Allows the user to set the max value allowed.
		 * @param maxValue	new max value allowed
		 */
		public void setMaxValue(int maxValue){
			this.maxValue = maxValue;
		}
	}
}
